package com.dotflat.photoAlbum.service.impl;

import com.dotflat.photoAlbum.domain.PhotoAlbumStatic;
import com.dotflat.photoAlbum.domain.PhotoAlbumStaticTemplate;
import com.dotflat.photoAlbum.domain.PhotoAlbumStaticTemplatePage;
import com.dotflat.photoAlbum.repository.PhotoAlbumStaticRepository;
import com.dotflat.photoAlbum.repository.PhotoAlbumTemplatePageRepository;
import com.dotflat.photoAlbum.repository.PhotoAlbumTemplateRepository;
import com.dotflat.photoAlbum.service.PhotoAlbumStaticPageService;
import com.starinside.wp.WpApplication;
import com.starinside.wp.domain.Children;
import com.starinside.wp.foundation.constant.LiveRecordConstant;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.repository.ChildrenRepository;
import com.starinside.wp.repository.LiveRecordRepository;
import com.starinside.wp.service.UploadService;
import com.tuo51.foudation.utils.CopyUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.starinside.wp.foundation.model.ErrorCode.JSON_STR_ERROR;
import static freemarker.template.Configuration.VERSION_2_3_26;

@Service
public class PhotoAlbumStaticPageServiceImpl implements PhotoAlbumStaticPageService {

    @Autowired
    PhotoAlbumStaticRepository albumRepository;

    @Autowired
    PhotoAlbumTemplatePageRepository pageRepository;

    @Autowired
    PhotoAlbumTemplateRepository templateRepository;

    @Autowired
    ChildrenRepository childrenRepository;

    @Autowired
    LiveRecordRepository liveRecordRepository;

//    @Autowired
//    ObservationNewRepository observationRepository;

    @Autowired
    UploadService uploadService;

    @Value("${album.photo.templateName}")
    String templateFileName;

    @Override
    public Page<PhotoAlbumStatic> childrenAlbumPage(String childrenId, String areaId, PagerQuery pagerQuery) {
        PageRequest pr = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());
        return albumRepository.findByChildrenIdAndAreaIdOrderByCreatedDesc(childrenId, areaId, pr );
    }

    @Override
    public PhotoAlbumStatic photoAlbumById(String albumId) {
        PhotoAlbumStatic ret = albumRepository.getOne(albumId);

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定相册不存在");
        }

        return ret;
    }

    @Override
    public PhotoAlbumStatic photoAlbumById(String areaId, String albumId) {
        PhotoAlbumStatic ret = albumRepository.getFirstByAreaIdAndId(areaId, albumId);

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定相册不存在");
        }

        return ret;
    }

    @Override
    public PhotoAlbumStatic requestPrintAlbum(String areaId, String albumId){
        PhotoAlbumStatic ret = albumRepository.getFirstByAreaIdAndId(areaId, albumId);

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定相册不存在");
        }

        ret.setRequestPrintAt(new Date());

        return ret;
    }

    @Override
    public PhotoAlbumStatic createPhotoAlbum(String childrenId, String areaId, String areaName, String json) {
        Children c = childrenRepository.getOne(childrenId);
        if(null == c){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        PhotoAlbumStatic pa = PhotoAlbumStatic.of(c.getName(), c.getId(), areaId, areaName, c.getNickName(), c.getGender(), json, 0, false);
        pa.setAreaName(areaName);
        albumRepository.save(pa);

        //TODO 静态化
        try {
            pa.setStaticURL(staticfyPhotoAlbum(CopyUtils.transBean2Map(pa)));
            albumRepository.save(pa);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(JSON_STR_ERROR, "静态化文件时出错");
        }

        return pa;
    }

//    @Override
//    public Page<String> getAllValidPhotoURL(String childrenId, String areaId, PagerQuery pagerQuery) {
//
//        PageRequest pr = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());
//
//        int mediaType = LiveRecordConstant.MediaType.IMG.codeOf();
//
//        //TODO: 这里改成vo
//        int beginRow = pagerQuery.getPageNum() * pagerQuery.getPageSize();
//        int size = pagerQuery.getPageSize();
//        List<LiveRecord> records = liveRecordRepository.findAllValidPhotos(areaId, childrenId, beginRow, size );
//        int count = liveRecordRepository.countValidPhotos(areaId, childrenId);
//
//        List<String> images = records.stream().map(k ->{
//            return k.getResourceUrl();
//        }).collect(Collectors.toList());
//
//        Page<String> result = new PageImpl<String>(images, pr, count);
//
//        return result;
//    }

    public List<PhotoAlbumStaticTemplate> getAllTemplates(String areaId){
        return templateRepository.findAllByAreaId(areaId);
    }

    public List<PhotoAlbumStaticTemplatePage> getAllTemplatePages(String templateId){
        return pageRepository.findAllByTemplateIdOrderByCapacityDesc(templateId);
    }



    ///// for static res

    //配置信息
    private static Configuration configuration = null;

    //这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
//    private static String templateFolder ;

    //临时文件写出路径
    private static final String tempPath =  "/tmp/photo_album";
            //PhotoAlbumTemplate.class.getClassLoader().getResource(".").getPath() + "temp";


    static {
        try {
            configuration = new Configuration(VERSION_2_3_26);
            configuration.setDefaultEncoding("utf-8");

            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            TemplateLoader tl = new ClassTemplateLoader(WpApplication.class,"/");
            configuration.setTemplateLoader(tl);

            //create folder
            File tf = new File(tempPath);
            if(!tf.exists()){
                Boolean success = tf.mkdirs();
                if(success){
                    System.out.println("create file success::" + tempPath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String staticfyPhotoAlbum(Map<String, Object> map)  {

        Writer out = null;

        String url = tempPath + "/" + map.get("id")+".html";

        try {
            Template temple = configuration.getTemplate(templateFileName);//获取模板

            out = new OutputStreamWriter(new FileOutputStream(url));//生成最终页面并写到文件

            temple.process(map, out);//处理

            String uploadedResult = uploadService.uploadStaticPhotoAlbum(url);

            return uploadedResult;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {

            }

            File file = new File(url);
            if(file.exists()) {
                file.delete();
            }
        }

        throw new BusinessException(JSON_STR_ERROR, "生成相册出错");
    }
}
